package Hot100.Heap;

import java.util.Comparator;
import java.util.PriorityQueue;

public class findKthLargest {
    public static void main(String[] args) {
        int[] nums = {3,2,3,1,2,4,5,5,6};
        int k = 4;
        System.out.println(new findKthLargest().findKthLargest(nums,k));
    }
    public int findKthLargest(int[] nums, int k) {
        //将找第k大转变为找第k个元素
        k = nums.length - k + 1;
        //使用大顶堆解决问题
        PriorityQueue<Integer> queue = new PriorityQueue<>(new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o2 - o1;
            }
        });
        for (int i = 0; i < nums.length; i++) {
            if(queue.size() < k){
                queue.add(nums[i]);
            }else {
                //小于等于和小于其实效果一样
                if(nums[i] < queue.peek()){
                    queue.poll();
                    queue.add(nums[i]);
                }
            }
        }
        return queue.peek();
    }
}
